<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>拖拽功能的实现</title>
  <style>
    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    .father {
      width: 80%;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 2px solid green;
      margin: auto;
      justify-content: space-around;
    }

    .father>div {
      width: 40%;
      border: 1px solid red;
      height: 150px;
    }

    .father>div:hover {
      cursor: -webkit-grab;
    }

    .father>div>img:active {
      cursor: -webkit-grabbing;
    }

    .son1 {
      background-color: rgba(250, 216, 216, 0.3);
    }

    .son2 {
      background-color: rgba(152, 245, 190, 0.3);
    }
  </style>
</head>

<body>
  <div class="father">
    <div class="son1">
      <!-- 必须要有draggable="true" id="drag1" -->
      <img src="./logo.png" draggable="true" id="drag1">
    </div>
    <div class="son2">

    </div>
  </div>
</body>
<script>
  "use strict";
  //获取元素
  const son1 = document.querySelector(".son1");
  const son2 = document.querySelector(".son2");
  const img = document.querySelector("img");

  const allowDrop = (ev) => {
    ev.preventDefault();
  }
  const drag = (ev) => {
    ev.dataTransfer.setData("Text", ev.target.id);
  }
  const drop = (ev) => {
    ev.preventDefault();
    let data = ev.dataTransfer.getData("Text");
    /* console.log(ev.target);
    console.log(ev.currentTarget); */
    ev.currentTarget.appendChild(document.getElementById(data));
    ev.currentTarget.appendChild(document.getElementById(data));
  }

  // 给元素注册事件
  img.addEventListener("dragstart", (e) => {
    drag(e);
  });

  son1.addEventListener("dragover", (e) => {
    allowDrop(e);
  });
  son1.addEventListener("drop", (e) => {
    drop(e);
  });


  son2.addEventListener("dragover", (e) => {
    allowDrop(e);
  });
  son2.addEventListener("drop", (e) => {
    drop(e);
  });
</script>

</html>